package com.weishi.tcp.callback.impl;

import cn.hutool.json.JSONUtil;
import com.weishi.common.enums.RedisConstants;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.config.BeanContext;
import com.weishi.project.speedometer.service.ISpeedometerService;
import com.weishi.project.speedometer.vo.DevInfo;
import com.weishi.tcp.callback.TCPSercallBack;
import com.weishi.tcp.tcpserver.TCPServer;
import com.weishi.tcp.vo.TcpMassageDataVo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;


public class TCPServercallBack implements TCPSercallBack {

    private String Name = "zou";

    private ISpeedometerService speedometerService;

    private String errorStr = "";

    private Map<SocketChannel, String> scMap = new HashMap<>();

    private static TCPServercallBack tcpServercallBack;

    public static TCPServercallBack getInstance() {
        if (tcpServercallBack == null) {
            tcpServercallBack = new TCPServercallBack();
        }
        return tcpServercallBack;
    }

    public TCPServercallBack() {
        this.speedometerService = BeanContext.getApplicationContext().getBean(ISpeedometerService.class);
    }

    private Logger logger = Logger.getLogger("TCPServercallBack");

    @Override
    public void disconnected(SocketChannel socketClients, String address) {
        logger.info(Name + "TCP客户端" + socketClients + "断开，地址为：" + address);
    }

    @Override
    public void mssageArrived(byte[] buffer, SocketChannel sc) {
        try {
            String mString = new String(buffer, "UTF-8");
            logger.info(scMap.get(sc) + "," + mString);
			if (StringUtils.isNotEmpty(errorStr)) {
				mString = errorStr + mString;
			}
			errorStr = "";

			//处理数据
            if(!mString.endsWith("}")){
                errorStr = mString;
            }else{
                String[] strArray = mString.split("}");
                for (String str : strArray) {
                    if(StringUtils.isEmpty(str)){
                        continue;
                    }
                    str += "}";
                    TcpMassageDataVo dataVo = JSONUtil.toBean(str, TcpMassageDataVo.class);
                    if (StringUtils.isEmpty(scMap.get(sc)) &&(dataVo.getMsgId().equals(TcpMassageDataVo.MsgTypeEnum.GPS.getMsgId()) ||
                            dataVo.getMsgId().equals(TcpMassageDataVo.MsgTypeEnum.ACCELERATION.getMsgId()))) {
                        scMap.put(sc, dataVo.getDeviceId());
                    }
                    speedometerService.addRealTimeData(dataVo);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void hasconnect(SocketChannel socketClient) {
        List<SocketChannel> SocketClients = TCPServer.getInstance().getSocketClients();
        for (SocketChannel key : SocketClients) {
            try {
                logger.info("客户端：" + key + ",ReIP：" + key.getRemoteAddress().toString() + ",LoIP:" + key.getLocalAddress().toString());
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
    }


    @Override
    public void iniResult(boolean rs, Integer port) {
        // TODO 自动生成的方法存根
        logger.info("port:" + port + ",TCPserver lisening...Reslut:" + rs);
    }

    @Override
    public void replyClient() {
        while (true) {
            try {
                for (SocketChannel sc : scMap.keySet()) {
                    if (sc.isConnected()) {
                        String dev_id = scMap.get(sc);
                        DevInfo devInfo = speedometerService.selectRealTimeDataByDevId(dev_id);
                        devInfo.setRealTime();
                        TCPServer tcpServer = TCPServer.getInstance();
                        tcpServer.TCPServerSendStrToClient(JSONUtil.toJsonStr(devInfo), sc);
                        logger.info("replyClient:"+dev_id+devInfo);
                    }else{
                        scMap.remove(sc);
                    }
                }
            } catch (Exception e) {
                logger.info("***************"+e.toString());
                e.printStackTrace();
            }


            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
